#include <sys/time.h>
#include <signal.h>
#include <time.h> // itimerspec
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h> // memset, strncpy

#define INTERVAL 40000000 // 40 ms in ns

// This struct is created to save information that will be needed by the timer,
// such as socket file descriptors, frame numbers and video captures.
typedef struct {
  int socket_fd;
  int frame_num;
  char* filename;
} send_frame_data;

// This function will be called when the timer ticks
void send_frame(union sigval sv_data) {

  struct send_frame_data *data = (struct send_frame_data *) sv_data.sival_ptr;
  // You may retrieve information from the caller using data->field_name
  // ...
  data->frame_num++;
  // get packet data
  // ..
  printf("sending frame %d on socket %d\n", data->frame_num, data->socket_fd);
  // send packet
  // ..
}

// The following snippet is used to stop a currently running timer. The current
// task is not interrupted, only future tasks are stopped.
void timer_stop(timer_t play_timer, struct itimerspec play_interval) {
	play_interval.it_interval.tv_sec = 0;
	play_interval.it_interval.tv_nsec = 0;
	play_interval.it_value.tv_sec = 0;
	play_interval.it_value.tv_nsec = 0;
    timer_settime(play_timer, 0, &play_interval, NULL);
}

// starts the timer
void timer_start(timer_t play_timer, struct itimerspec play_interval) {
    play_interval.it_interval.tv_sec = 0;
	play_interval.it_interval.tv_nsec = INTERVAL;
	play_interval.it_value.tv_sec = 0;
	play_interval.it_value.tv_nsec = 1; // can't be zero
	timer_settime(play_timer, 0, &play_interval, NULL);
}

void timer_init

int main(int argc, char *argv[]) {
	// The following snippet is used to create and start a new timer that runs
	// every 40 ms.
	struct send_frame_data data; // Set fields as necessary
	struct sigevent play_event;
	timer_t play_timer;
	struct itimerspec play_interval;

	data.socket_fd = 4500;
	data.frame_num = 0;

	memset(&play_event, 0, sizeof(play_event));
	play_event.sigev_notify = SIGEV_THREAD;
	play_event.sigev_value.sival_ptr = &data;
	play_event.sigev_notify_function = send_frame;

	timer_create(CLOCK_REALTIME, &play_event, &play_timer);
	//timer_settime(play_timer, 0, &play_interval, NULL);


    printf("1. start timer\n");
	timer_start(play_timer, play_interval);
	sleep(1);
	printf("2. stop timer\n");
	timer_stop(play_timer, play_interval);
	sleep(1);
	printf("3. start timer\n");
	timer_start(play_timer, play_interval);
	sleep(1);
	printf("4. delete timer\n");
	timer_delete(play_timer);
	sleep(1);
	printf("5. play timer\n");
	timer_start(play_timer, play_interval);

	sleep(5);
}
